package com.hsh.maoduo.service.impl;

import com.hsh.maoduo.common.Result;
import com.hsh.maoduo.constant.YDPathConstants;
import com.hsh.maoduo.constant.YTGJPathConstants;
import com.hsh.maoduo.constant.common.DateConstants;
import com.hsh.maoduo.constant.common.GlobalPathConstants;
import com.hsh.maoduo.pojo.dto.ShopGoodsDTO;
import com.hsh.maoduo.pojo.other.yt.*;
import com.hsh.maoduo.pojo.vo.ShopGoodsVO;
import com.hsh.maoduo.service.GoodsService;
import com.hsh.maoduo.service.OrderGoodsService;
import com.hsh.maoduo.service.ShopGoodsService;
import com.hsh.maoduo.service.YTGJService;
import com.hsh.maoduo.util.MyBeanUtils;
import com.hsh.maoduo.util.POIExcelUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class YTGJServiceImpl implements YTGJService {

    @Resource
    private OrderGoodsService orderGoodsService;

    @Resource
    private ShopGoodsService shopGoodsService;

    @Resource
    private GoodsService goodsService;

    @Override
    public Result writeSendExcel(String dateStr) {
        String pddMsg = writePddSendExcel(dateStr);
        String mtMsg = writeMtSendExcel(dateStr);
        return Result.success(pddMsg + mtMsg);
    }


    /**
     * @param mtPassword
     * @return
     */
    @Override
    public int writeImportExcel(String mtPassword) {
        String dateStr = DateConstants.PURE_DATE_FORMAT.format(new Date());
        List<PDDHandBillImport> PDDHandBillImportList = mtExportsToYTGJImports(mtPassword);
        int rowNum = POIExcelUtil.write(YTGJPathConstants.IMPORT_PATH_PRE
                        + YTGJPathConstants.YTGJ_IMPORT_NAME_PRE
                        + dateStr
                        + GlobalPathConstants.XLSX_SUF
                , PDDHandBillImportList, PDDHandBillImport.class);
        return rowNum;
    }

    private String writeMtSendExcel(String dateStr) {
        //读取圆通国际导出文件
        List<YTGJMTExport> YTGJExportList = POIExcelUtil.reads(YTGJPathConstants.EXPORT_PATH_PRE
                , YTGJPathConstants.MT_EXPORT_NAME_PRE + dateStr
                , YTGJMTExport.class);
        //将读取的圆通国际数据转成order并写入数据库
        int insertOrderNum = orderGoodsService.insertByExport(YTGJExportList);
        //处理导出文件中的数据
        List<YTGJCollect> YTGJCollectList = new ArrayList<>();
        for (YTGJMTExport YTGJExport : YTGJExportList) {
            //构建揽收文件的数据
            YTGJCollectList.add(new YTGJCollect(YTGJExport.getExpressNum()));
        }
        //写入圆通国际揽收文件
        int ytRowNum = POIExcelUtil.write(YTGJPathConstants.SEND_PATH_PRE
                        + YTGJPathConstants.YT_IMPORT_NAME_PRE
                        + dateStr
                        + GlobalPathConstants.XLSX_SUF
                , YTGJCollectList, YTGJCollect.class);
        //写入到圆通国际总揽收表
        int allYtRowNum = POIExcelUtil.write(YTGJPathConstants.ALL_YTGJ_SEND_PATH_PRE
                        + YTGJPathConstants.YT_IMPORT_NAME_PRE
                        + dateStr
                        + GlobalPathConstants.XLSX_SUF
                , YTGJCollectList, YTGJCollect.class);
        writeSendMtExcel(YTGJExportList, dateStr);
        return "美团-圆通国际<br>新增订单数量：" + insertOrderNum + "，写入揽收文件数量：" + allYtRowNum + "<br>-----------------------------<br>";
    }

    /**
     * 写入到 美团批量发货文档
     *
     * @param ytgjMtExportList
     * @param dateStr
     */
    private int writeSendMtExcel(List<YTGJMTExport> ytgjMtExportList, String dateStr) {
        List<MTSendGoods> MTSendGoodsList = new ArrayList<>();
        ytgjMtExportList.stream().forEach(v -> MTSendGoodsList.add(new MTSendGoods(v.getOrderNo(), v.getExpressNum())));
        //写入到美团批量发货文档
        int rowNum = POIExcelUtil.write(YTGJPathConstants.SEND_MT_PATH_PRE
                        + YTGJPathConstants.MT_SEND_NAME_PRE
                        + dateStr
                        + GlobalPathConstants.XLSX_SUF
                , MTSendGoodsList, MTSendGoods.class);
        return rowNum;
    }

    private String writePddSendExcel(String dateStr) {
        //读取圆通国际导出文件
        List<YTGJPDDExport> YTGJPDDExportList = POIExcelUtil.reads(YTGJPathConstants.PDD_EXPORT_PATH_PRE
                , YTGJPathConstants.PDD_EXPORT_NAME_PRE + dateStr
                , YTGJPDDExport.class);
        //将读取的圆通国际数据转成order并写入数据库
        int insertOrderNum = orderGoodsService.insertByExport(YTGJPDDExportList);
        //处理导出文件中的数据
        List<YTGJCollect> YTGJCollectList = new ArrayList<>();
        for (YTGJPDDExport YTGJPDDExport : YTGJPDDExportList) {
            //构建揽收文件的数据
            YTGJCollectList.add(new YTGJCollect(YTGJPDDExport.getExpressNum()));
        }
        //写入圆通国际揽收文件
        int ytRowNum = POIExcelUtil.write(YTGJPathConstants.YT_IMPORT_PATH_PRE
                        + YTGJPathConstants.YT_IMPORT_NAME_PRE
                        + dateStr
                        + GlobalPathConstants.XLSX_SUF
                , YTGJCollectList, YTGJCollect.class);
        //写入到圆通国际总揽收表
        int allYtRowNum = POIExcelUtil.write(YTGJPathConstants.ALL_YTGJ_SEND_PATH_PRE
                        + YTGJPathConstants.YT_IMPORT_NAME_PRE
                        + dateStr
                        + GlobalPathConstants.XLSX_SUF
                , YTGJCollectList, YTGJCollect.class);
        return "拼多多-圆通国际<br>新增订单数量：" + insertOrderNum + "，写入揽收文件数量：" + allYtRowNum + "<br>-----------------------------<br>";
    }


    /**
     * 读取美团导出文档并筛选符合条件的数据
     *
     * @param mtPassword 美团密码
     * @return ytgjImportList 已有数据的韵达导入文件
     */
    private List<PDDHandBillImport> mtExportsToYTGJImports(String mtPassword) {
        List<PDDHandBillImport> PDDHandBillImportList = new ArrayList<>();
        //读取美团导出文档
        List<MTExport> mtExportList = POIExcelUtil.reads(YTGJPathConstants.MT_EXPORT_PATH_PRE
                , YTGJPathConstants.MT_EXPORT_NAME_PRE + DateConstants.NORM_DATE_FORMAT.format(new Date())
                , MTExport.class, mtPassword);
        //一个订单有多个商品时
        for (int i = 0; i < mtExportList.size(); i++) {
            setMtExportGoodsInfo(i, mtExportList);
        }
        //筛选符合条件的数据
        mtExportList = mtExportList.stream()
                .filter(v -> YDPathConstants.MT_ORDER_STATE_WAIT_SEND.equals(v.getSendState()))//状态为待发配送
//                .filter(v -> !GoodsStrEnums.contains(v.getGoodsInfo()))//移除 商品信息为邮费 的记录
                //todo 暂时先去除4.17之前的订单
                .filter(v -> DateConstants.dateTimeParse(v.getOrderTime()).after(DateConstants.dateTimeParse("2024-04-17 12:00:00")))
                .collect(Collectors.toList());
        //反转集合，下单时间早的放在前面
        Collections.reverse(mtExportList);
        //去除库存不足的订单
        mtExportList = goodsService.removeOutOfStockOrders(mtExportList);
        //遍历每条数据  美团导出 -> 韵达导入
        for (MTExport mtExport : mtExportList) {
            PDDHandBillImport PDDHandBillImport = MyBeanUtils.copy(mtExport, PDDHandBillImport.class);
            PDDHandBillImport.init();
            PDDHandBillImportList.add(PDDHandBillImport);
        }
        return PDDHandBillImportList;
    }


    /**
     * 去除库存不足的订单
     *
     * @param mtExportList 导入的集合
     * @return mtExportList
     */
//    private List<MTExport> removeOutOfStockOrders(List<MTExport> mtExportList) {
//    List<MTExport> inStcokList = new ArrayList<>();
//    //有库存的商品集合
//    List<Goods> inStockGoods = goodsService.getInStockGoods();
//        for (MTExport mtExport : mtExportList) {
//        if (Strings.isBlank(mtExport.getGoodsInfo())) {
//            continue;
//        }
//        for (Goods inStockGood : inStockGoods) {
//            boolean haveGoods = DataUtil.include(mtExport.getGoodsInfo(), inStockGood.getGoodsName())
//                    || DataUtil.include(mtExport.getGoodsInfo(), inStockGood.getSimpleGoodsName());
//            boolean haveStock = mtExport.getNum() <= inStockGood.getNum();
//            if (haveGoods && haveStock) {
//                //库存足够时，加入到结果集中
//                inStcokList.add(mtExport);
//                //修改商品剩余库存
//                inStockGood.setNum(inStockGood.getNum() - mtExport.getNum());
//                break;
//            }
//        }
//    }
//        return inStcokList;
//}


    /**
     * 设置商品的商品信息，格式为： 名称 * 数量
     * 一个订单有多个商品时
     * ,将没有订单号的数据填充到上面第一个非空的商品信息中
     *
     * @param mtExportList 导入的集合
     * @param index        当前行的下标
     * @return index 返回共用数据的下标
     */
    private int setMtExportGoodsInfo(int index, List<MTExport> mtExportList) {
        MTExport mtExport = mtExportList.get(index);
        //根据商品编码和数量获得商品信息：   名称 * 数量
        setGoodsInfoByBarcode(mtExport);
        if (Strings.isBlank(mtExport.getGoodsName())) {
            return 0;
        }
        //第一行一般不为空，超出list下标的不处理
        if (index == 0 || index > mtExportList.size() - 1) {
            return 0;
        }
        //数据不为空的无需处理
        if (Strings.isNotBlank(mtExport.getCustomName())) {
            return index;
        }
        //如果当前订单没有订单号，使用上一行的订单号
        int perIndex = setMtExportGoodsInfo(index - 1, mtExportList);
        MTExport perMTExport = mtExportList.get(perIndex);
        perMTExport.setGoodsInfo(perMTExport.getGoodsInfo() + "；" + mtExport.getGoodsInfo());
        perMTExport.setWeight(perMTExport.getWeight() + mtExport.getWeight());
        return perIndex;
    }


    public MTExport setGoodsInfoByBarcode(MTExport mtExport) {
        List<ShopGoodsDTO> shopGoodsDTOList = shopGoodsService.selectGoodsNameList(new ShopGoodsVO());
        Map<String, ShopGoodsDTO> goodsInfoMap =
                shopGoodsDTOList.stream().collect(Collectors.toMap(ShopGoodsDTO::getShopGoodsId, Function.identity()));
        //商品信息 = 商品简称 * 商品数量
        String goodsSimpleName = "";
        Integer weight = 0;
        ShopGoodsDTO shopGoodsDTO = goodsInfoMap.get(mtExport.getBarcode());
        if (shopGoodsDTO != null) {
            goodsSimpleName = shopGoodsDTO.getGoodsInfo();
            weight = shopGoodsDTO.getWeight();
        }
        if (Strings.isBlank(goodsSimpleName)) {
            //获取商品名称失败
            goodsSimpleName = YDPathConstants.DEFAULT_SIMPLE_NAME;
        }
        int num = mtExport.getNum();
        //商品名称为 名称 * 数量时
        if (goodsSimpleName.matches(".*\\*\\d+")) {
            String[] split = goodsSimpleName.split("\\*");
            goodsSimpleName = split[0];
            num *= Integer.parseInt(split[1]);
        }
        mtExport.setGoodsInfo(goodsSimpleName + "*" + num);
        mtExport.setGoodsName(goodsSimpleName);
        mtExport.setNum(num);
        weight = weight == null ? 0 : weight;
        mtExport.setWeight(weight * num);
        return mtExport;
    }
}
